
package lagrangepolynomial;


public class Polynomial implements DrawableFunction {
    
    private final Function func;
    private int n;
    double x0, h;
    
    public Polynomial(Function func, int n, int l, int r) {
        this.func = func;
        this.n = n - 1;
        this.x0 = l;
        this.h = (r-l)/(n-1);
    }
    
    @Override
    public double f(double x) {
        double L = 0;
        double s;
        for (int i = 0; i <= n; i++) {
            s = 1;
            for (int j = 0; j <= n; j++)
                if (j != i)
                    s *= (x - (x0 + j*h))/(h*(i - j));
            L += func.f(x0 + i*h)*s;
        }
        return L;
    }
    
}
